package com.wechat.controller;

import com.alibaba.fastjson.JSONObject;
import com.fh.modules.oms.vo.OrderVo;
import com.fhMall.request.OrderReturnApplyRequest;
import com.fhMall.request.QueryOrderListRequest;
import com.fhMall.request.SubmitOrderRequest;
import com.fhMall.request.WechatOrderReturnHandleResquest;
import com.wechat.core.annotation.Token;
import com.wechat.core.bean.Result;
import com.wechat.feign.FhEmallOrderApi;
import com.wechat.models.response.WxOrderDetailResponse;
import com.wechat.service.order.WechatOrderService;
import com.wechat.util.CodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * 程序名：.java<br>
 * 程序功能 <br>
 * 作成者：xianlin <br>
 * 日期：2019-09-19 20:46<br>
 * 修改履历 <br>
 * 项目名    状态      作成者      日期   <br>
 * --------------------------------------- <br>
 * 新规      xianlin   2019-09-19 20:46 <br>
 * ----------------------------- <br>
 */
@RestController
@RequestMapping("wechat/order")
@Api(tags = "微商城订单")
@Slf4j
public class WechatOrderController extends BaseController{

    @Autowired
    private WechatOrderService wechatOrderService;

    @Autowired
    private FhEmallOrderApi fhEmallOrderApi;

    /**
     * 立即预定--下单
     * @param submitOrderRequest
     * @param request
     * @return 预支付参数
     */
    @ApiOperation(value = "立即预定--下单")
    @PostMapping(value = "/submitOrder")
    public Result submitOrder(@RequestBody SubmitOrderRequest submitOrderRequest, HttpServletRequest request) {
        String ipAddr = CodeUtil.getIpAddr(request);
        submitOrderRequest.setMemberId(this.getUserId());
        return new Result<>().result(wechatOrderService.submitOrder(submitOrderRequest, this.getOpenId(), ipAddr));
    }

    @ApiOperation(value = "再次支付")
    @PostMapping(value = "/payAgain")
    public Result payAgain(Integer id, HttpServletRequest request) {
        String ipAddr = CodeUtil.getIpAddr(request);
        return new Result<>().result(wechatOrderService.payAgain(id,this.getUserId(), this.getOpenId(), ipAddr));
    }

    @ApiOperation(value = "订单列表")
    @PostMapping(value = "/orderList")
    public JSONObject queryOrderList(@RequestBody OrderVo orderVo) {
        orderVo.setMemberId(this.getUserId());
        String result = fhEmallOrderApi.queryOrderList(orderVo);
        return JSONObject.parseObject(result);
    }

    @ApiOperation(value = "订单详情", response = WxOrderDetailResponse.class)
    @GetMapping(value = "/detail")
    public JSONObject details(@RequestParam(name = "id") String id) {
        String result = fhEmallOrderApi.queryOrderInfo(id);
        return JSONObject.parseObject(result);
    }

    @ApiOperation(value = "取消订单", response = WxOrderDetailResponse.class)
    @PostMapping(value = "/cancelOrder")
    public JSONObject cancelOrder(@ApiParam("订单id") @RequestParam(name = "id") Integer id) {
        String result = fhEmallOrderApi.cancelOrder(id);
        return JSONObject.parseObject(result);
    }

    @ApiOperation(value = "删除订单", response = WxOrderDetailResponse.class)
    @DeleteMapping(value = "/deleteOrder")
    public JSONObject deleteOrder(@ApiParam("订单id") @RequestParam(name = "id") Integer id) {
        String result = fhEmallOrderApi.deleteOrder(id);
        return JSONObject.parseObject(result);
    }

    @PostMapping(value = "/confirmRecieve")
    @ApiOperation("确认收货")
    public JSONObject confirmRecieve(Integer orderId) {
        String result = fhEmallOrderApi.confirmRecieve(orderId,this.getUserId());
        return JSONObject.parseObject(result);
    }

    @PostMapping(value = "/applyRefund")
    @ApiOperation(value = "提交-申请退款")
    public JSONObject applyRefund(@RequestBody OrderReturnApplyRequest orderReturnApplyRequest) {
        orderReturnApplyRequest.setMemberId(this.getUserId());
        String result = fhEmallOrderApi.orderReturnApply(orderReturnApplyRequest);
        return JSONObject.parseObject(result);
    }

    @PostMapping(value = "/handleRefund")
    @ApiOperation(value = "退款")
    @Token(required = false)
    public JSONObject handleRefund(@RequestBody WechatOrderReturnHandleResquest wechatOrderReturnHandleResquest) {

        return wechatOrderService.handleRefund(wechatOrderReturnHandleResquest);
    }

    @RequestMapping(value = "/paySuccessNotify")
    @ApiOperation("微信订单支付通知notify")
    @Token(required = false)
    public void paySuccess(HttpServletRequest request, HttpServletResponse response) {
        log.info("微信支付返回通知开始---------------------");
        try {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");
            String noticeStr = wechatOrderService.paySuccess(result);

            PrintWriter writer = response.getWriter();
            writer.write(noticeStr);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping(value = "/refundSuccessNotify")
    @ApiOperation("微信订单退款通知notify")
    @Token(required = false)
    public void refundSuccess(HttpServletRequest request, HttpServletResponse response) {
        log.info("微信退款返回通知开始---------------------");
        try {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");
            String noticeStr = wechatOrderService.refundSuccess(result);

            PrintWriter writer = response.getWriter();
            writer.write(noticeStr);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
